/*
 * COPYRIGHT. ShenZhen JiMi Technology Co., Ltd. 2022.
 * ALL RIGHTS RESERVED.
 *
 * No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
 * on any form or by any means, electronic, mechanical, photocopying, recording, 
 * or otherwise, without the prior written permission of ShenZhen JiMi Network Technology Co., Ltd.
 *
 * Amendment History:
 * 
 * Date                   By              Description
 * -------------------    -----------     -------------------------------------------
 * 2022年10月17日    Tony         Create the class
 * http://www.jimilab.com/
*/

package com.futuremap.ws.util;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import io.netty.channel.Channel;

/**
 * @FileName ChannelSupervise.java
 * @Description: 
 *
 * @Date 2022年10月17日 上午11:57:22
 * @author Tony
 * @version 1.0
 */
public class ChannelSupervise {
	
	private  static ConcurrentMap<String, List<Channel>> ChannelMap = new ConcurrentHashMap<>();
	
	public  static void registerChannel(String userId, Channel channel){
		//同一个用户可能涉及多个连接
		List<Channel> list = ChannelMap.get(userId);
		if(list == null)
		{
			list = new LinkedList<>();
			ChannelMap.put(userId, list);
		}
		list.add(channel);
	}
	
	public  static void unRegisterChannel(String userId, Channel channel){
		List<Channel> list = ChannelMap.get(userId);
		if(list != null && list.size() > 0)
		{
			for(int i=0;i<list.size();i++)
			{
				Channel c = list.get(i);
				if(c.id().equals(channel.id()))
				{
					if(channel.isActive())
					{
						channel.close();
					}
					list.remove(i);
				}
			}
			if(list.size() == 0)
			{
				ChannelMap.remove(userId);
			}
		}
	}
	
	public  static List<Channel> getChannel(String userId){
		//同一个用户可能涉及多个连接
		List<Channel> list = ChannelMap.get(userId);
		return list;
	}

//	private  static ChannelGroup GlobalGroup=new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
//    private  static ConcurrentMap<String, ChannelId> ChannelMap=new ConcurrentHashMap();
//    
//    public  static void addChannel(Channel channel){
//        GlobalGroup.add(channel);
//        ChannelMap.put(channel.id().asShortText(),channel.id());
//    }
//    public static void removeChannel(Channel channel){
//        GlobalGroup.remove(channel);
//        ChannelMap.remove(channel.id().asShortText());
//    }
//    
//    public static  Channel findChannel(String id){
//        return GlobalGroup.find(ChannelMap.get(id));
//    }
//    
//    public static void send2All(TextWebSocketFrame tws){
//        GlobalGroup.writeAndFlush(tws);
//    }
}
